package com.cxkj.camera2_plugin;

import android.app.Activity;
import android.util.Base64;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import com.alibaba.fastjson.JSONObject;
import io.dcloud.feature.uniapp.annotation.UniJSMethod;
import io.dcloud.feature.uniapp.bridge.UniJSCallback;
import io.dcloud.feature.uniapp.common.UniModule;


public class CameraModule extends UniModule {
    private CameraPreviewView cameraView;

    @UniJSMethod(uiThread = true)
    public void startPreview(UniJSCallback callback) {
        Activity activity = (Activity) mUniSDKInstance.getContext();
        cameraView = new CameraPreviewView(activity);
        FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(600, 600);
        layoutParams.leftMargin = 100;
        layoutParams.topMargin = 200;
        activity.addContentView(cameraView, layoutParams);
        callback.invoke("Camera preview started");
    }

    @UniJSMethod(uiThread = true)
    public void takePhoto(UniJSCallback callback) {
        if (cameraView != null) {
            cameraView.takePicture((data, camera) -> {
                String base64 = Base64.encodeToString(data, Base64.NO_WRAP);
                JSONObject result = new JSONObject();
                result.put("base64", base64);
                callback.invoke(result);
                camera.startPreview();
            });
        }
    }

    @UniJSMethod(uiThread = true)
    public void stopPreview(UniJSCallback callback) {
        if (cameraView != null && cameraView.getParent() != null) {
            ((ViewGroup) cameraView.getParent()).removeView(cameraView);
            cameraView.stopCamera();
            cameraView = null;
        }
        callback.invoke("Camera stopped");
    }
}
